﻿@model TWCRM.Models.Home.OrderModel
@{
    Layout = "/Views/Shared/_SubLayout.cshtml";
    ViewBag.Title = "訂單";
}
<link href="@Url.Content("~/Scripts/jquery-ui-1.8.23.custom/css/custom-theme/jquery-ui-1.8.23.custom.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.23.custom/js/jquery-ui-1.8.23.custom.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.23.custom/development-bundle/ui/i18n/jquery.ui.datepicker-zh-TW.js")" type="text/javascript"></script>
<style>
    .metro_input_dropdownselect
    {
        max-height: 300px;
        overflow: auto;
    }
    
    .customerValue
    {
        display: inline-block;
    }
    
    #TotalPrice
    {
        font-size: 1.2em;
        font-weight: bold;
    }
</style>
<script>
    var isNew = true;
    $(document).ready(function () {
        isNew = $.url().param('id') == undefined;

        if (isNew)
            $('.metro_input_contain input:first').focus();

        $.fn.metro.onPrevClick = function () {
            window.history.go(-1);
        };

        adjustMetroInputContain();

        //初始化日期控件
        $("#Date").datepicker();

        //加載客戶列表
        loadCustomers();

        //添加已有order detail
        if (!isNew) {
            addOrderDetails();
        }

        //初始化order detail grid
        $('.metro_grid').metro_grid();

        //window.resize
        $(window).resize(function () {
            //調整product selector位置
            adjustProductSelector();
        });
    });
</script>
<!--客戶列表  行模版-->
<script id="customerItemTemplate" type="text/x-jquery-tmpl">
    <li class="customerItem" customerID="${ID}">${FirstName} ${LastName}</li>
</script>
<!--產品類別 树模版-->
<script id="treeNodeTemplate" type="text/x-jquery-tmpl">
    {{if Children.length}}
        <li class="expandable">
            <div class="hitarea expandable-hitarea"></div>
            <div class="treeNode" productTypeID="${ID}">${Name}</div>
            <ul style="display: none;">
                {{tmpl(Children) "#treeNodeTemplate"}}
            </ul>
        </li>
    {{else}}
        <li>
            <div class="treeNode" productTypeID="${ID}">${Name}</div>
        </li>
    {{/if}}
</script>
<!--產品列表 行模版-->
<script id="metroGridRowTemplate" type="text/x-jquery-tmpl">
    <div class="metro_grid_row">
        <div class="metro_grid_cell hide"><div class="productID">${ID}</div></div>
        <div class="metro_grid_cell hide"><div class="productPrice">${ListPrice}</div></div>
        <div class="metro_grid_cell hide"><div class="productType">${ProductType}</div></div>
        <div class="metro_grid_cell"><div class="productName">${Name}</div></div>
        <div class="metro_grid_cell"><div class="productBrand">${Brand}</div></div>
        <div class="metro_grid_cell"><div class="productModel">${Model1}</div></div>
        <div class="metro_grid_cell"><div>${ListPriceStr}</div></div>
        <div class="clear">
        </div>
    </div>
</script>
<!--產品列表模版-->
<script id="metroGridTemplate" type="text/x-jquery-tmpl">
    <div class="metro_grid product">
        <div class="metro_grid_contain">
            <div class="metro_grid_header">
                <div class="metro_grid_column hide"><div></div></div>
                <div class="metro_grid_column hide"><div></div></div>
                <div class="metro_grid_column hide"><div></div></div>
                <div class="metro_grid_column" data-width="201">
                    <div>名稱</div></div>
                <div class="metro_grid_column" data-width="130">
                    <div>品牌</div></div>
                <div class="metro_grid_column" data-width="130">
                    <div>型號</div></div>
                <div class="metro_grid_column" data-width="80">
                    <div>標價</div></div>
                <div class="clear">
                </div>
            </div>
            <div class="metro_grid_rows">
                {{tmpl(List) "#metroGridRowTemplate"}}
            </div>
        </div>
    </div>
</script>
<!--訂單明細列表 行模版-->
<script id="metroGridRowTemplate_OrderDetail" type="text/x-jquery-tmpl">
    <div class="metro_grid_row">
        <div class="metro_grid_cell hide"><div class="productID">${ProductID}</div></div>
        <div class="metro_grid_cell"><div class="od_Name">${ProductName}</div></div>
        <div class="metro_grid_cell"><div class="od_Type">${ProductType}</div></div>
        <div class="metro_grid_cell"><div class="od_Brand">${ProductBrand}</div></div>
        <div class="metro_grid_cell"><div class="od_Model">${ProductModel}</div></div>
        <div class="metro_grid_cell"><div class="od_ListPrice">${ListPrice}</div></div>
        <div class="metro_grid_cell"><input value="${Price}" class="od_Price"></input></div>
        <div class="metro_grid_cell"><input value="${Qty}" class="od_Qty"></input></div>
        <div class="metro_grid_cell"><div class="od_TotalPrice" od_TotalPrice="${TotalPrice}">${TotalPriceStr}</div></div>
        <div class="clear">
        </div>
    </div>
</script>
<script id="metroGridRowTemplate_OrderDetail_NewProduct" type="text/x-jquery-tmpl">
    <div class="metro_grid_row">
        <div class="metro_grid_cell hide"><div class="productID">00000000-0000-0000-0000-000000000000</div></div>
        <div class="metro_grid_cell"><input value="${ProductName}" class="od_Name"></input></div>
        <div class="metro_grid_cell"><input value="${ProductType}" class="od_Type"></input></div>
        <div class="metro_grid_cell"><input value="${ProductBrand}" class="od_Brand"></input></div>
        <div class="metro_grid_cell"><input value="${ProductModel}" class="od_Model"></input></div>
        <div class="metro_grid_cell"><div class="od_ListPrice">${ListPrice}</div></div>
        <div class="metro_grid_cell"><input value="${Price}" class="od_Price"></input></div>
        <div class="metro_grid_ cell"><input value="${Qty}" class="od_Qty"></input></div>
        <div class="metro_grid_cell"><div class="od_TotalPrice" od_TotalPrice="${TotalPrice}">${TotalPriceStr}</div></div>
        <div class="clear">
        </div>
    </div>
</script>
<div id="OrderEdit">
    @using (Html.BeginForm())
    {
        @Html.HiddenFor(m => m.ID)
        @Html.HiddenFor(m => m.IsNew)
        <div class="metro_toolbar">
            <div class="metro_input_contain">
                <a class="metro_input_btn" onclick="confirm()">儲存訂單</a> <a class="metro_input_btn"
                    onclick="openSelectProduct()">選擇產品</a> <a class="metro_input_btn" onclick="newProduct()">
                        新增未登记產品</a> <a class="metro_input_btn" onclick="removeProduct()">移除產品</a>
            </div>
        </div>
        <div class="metro_input_contain customer">
            <label for="Customer" class="metro_input_caption">
                客戶
            </label>
            <div class="metro_input_dropdownselect">
                <ul class="listview" id="customerList">
                </ul>
            </div>
            <label class="metro_input_trigger_dropdown one_line">
                <a class="metro_input_select_btn"><span class="customerValue">@Model.Customer</span>
                    <span class="metro_trigger_dropdown">▼</span></a>
            </label>
            @Html.HiddenFor(m => m.CustomerID)
        </div>
        <div class="metro_input_contain_inline_block">
            <div class="metro_input_contain">
                <label for="Date" class="metro_input_caption">
                    日期
                </label>
                <input type="text" id="Date" name="Date" class="metro_input_textinput two_line" value='@Model.Date.ToString("yyyy-MM-dd")'>
            </div>
            <div class="metro_input_contain">
                <label for="TotalPrice" class="metro_input_caption">
                    總計
                </label>
                <label class="metro_input_display two_line" id="TotalPrice">@Model.TotalPrice</label>
            </div>
        </div>
        <div class="part_caption">
            <p class="part_caption_text">
                訂單明細</p>
            <p class="part_caption_line">
            </p>
        </div>
        <div class="metro_grid orderDetail">
            <div class="metro_grid_contain">
                <div class="metro_grid_header">
                    <div class="metro_grid_column hide">
                        <div>
                        </div>
                    </div>
                    <div class="metro_grid_column" data-width="170">
                        <div>
                            名稱</div>
                    </div>
                    <div class="metro_grid_column" data-width="auto">
                        <div>
                            類別</div>
                    </div>
                    <div class="metro_grid_column" data-width="120">
                        <div>
                            品牌</div>
                    </div>
                    <div class="metro_grid_column" data-width="120">
                        <div>
                            型號</div>
                    </div>
                    <div class="metro_grid_column" data-width="100">
                        <div>
                            標價</div>
                    </div>
                    <div class="metro_grid_column" data-width="100">
                        <div>
                            實際價格</div>
                    </div>
                    <div class="metro_grid_column" data-width="100">
                        <div>
                            數量</div>
                    </div>
                    <div class="metro_grid_column" data-width="100">
                        <div>
                            小計</div>
                    </div>
                    <div class="clear">
                    </div>
                </div>
                <div class="metro_grid_rows">
                </div>
            </div>
        </div>
        @Html.HiddenFor(m => m.OrderDetail, new { @class = "txt_OrderDetail" })
    }
</div>
<div id="ProductSelector" class="product_selector">
    <div class="product_selector_contain">
        <div class="product_selector_caption">
            <span>選擇產品</span>
            <div class="metro_input_contain">
                <a class="metro_input_btn" onclick="cancelSelectProduct()">取消</a> <a class="metro_input_btn"
                    onclick="confirmSelectProduct()">確定</a>
            </div>
        </div>
        <div class="product_selector_content">
            <div class="product_selector_content_producttypes">
                <ul class="treeview" id="tree">
                </ul>
            </div>
            <div class="product_selector_content_products">
            </div>
            <div class="clear">
            </div>
        </div>
    </div>
</div>
<script>
    //提交
    function confirm() {
        if (!valEmptyH($(".customerValue"))) {
            showError("客戶是必要欄位不可留白");
            return;
        }

        if (!valEmpty($("#Date"))) {
            showError("日期是必要欄位不可留白");
            return;
        }

        var orderDetail = '';
        $('.metro_grid_row','.orderDetail').each(function () {
            var $row = $(this);
            var od_pid = $('.productID',$row).html();
            var od_pname = $('.od_Name', $row).val();
            var od_ptype = $('.od_Type', $row).val();
            var od_pbrand = $('.od_Brand',$row).val();
            var od_pmodel = $('.od_Model',$row).val();
            var od_pprice = $('.od_Price', $row).val();
            var od_pqty = $('.od_Qty', $row).val();
            orderDetail += od_pid + "●" + od_pname + "●" + od_ptype + "●" + od_pbrand + "●" + od_pmodel + "●" + od_pprice + "●" + od_pqty + "◆";
        });
        $('.txt_OrderDetail').val(orderDetail);

        showLoading();
        $('form').submit();
    }
    //初始化下拉選擇器
    function initDropdown($part) {
        var $current_trigger_dropdown;
        //綁定下拉選擇器的小倒三角按鈕點擊事件
        $('.metro_input_trigger_dropdown', $part).unbind('click').bind('click', function (e) {
            //阻止事件冒泡
            e.stopPropagation();
            $current_trigger_dropdown = $(this);
            $('.metro_input_dropdownselect', $part).css({ left: $current_trigger_dropdown.position().left });
            $('.metro_input_dropdownselect', $part).width($current_trigger_dropdown.width() - 2);
            $('.metro_input_dropdownselect', $part).show();
        });
        $('.metro_input_dropdownselect li', $part).hover(function () {
            $(this).addClass('hover');
        }, function () {
            $(this).removeClass('hover');
        });
        //綁定item的點擊事件
        $('.customerItem', $part).unbind('click').bind('click', function () {
            //將顯示值賦值到.customerValue
            $('.customerValue', $part).html($(this).html());
            //將選中的CustomerID賦值到#CustomerID
            $('#CustomerID', $part).val($(this).attr('customerID'));
            //關閉下拉選擇器
            $('.metro_input_dropdownselect', $part).hide();
        });
    }
    //加載客戶
    function loadCustomers() {
        //顯示加載畫面
        showLoading();
        var url = "/Home/GetCustomers";
        $.ajax({
            url: url,         //请求链接 
            dataType: "json",
            success: function (result) {
                $('#customerItemTemplate').tmpl(result.List).appendTo($('#customerList'));
                //初始化下拉選擇器
                initDropdown($('.customer'));
                //隱藏加載提示
                hideLoading();
            }
        });
    }
    //緩存ProductType
    var productTypes;
    //加載ProductType
    function loadProductTypes() {
        //判斷是否已經加載過
        if (productTypes != undefined)
            return;
        //顯示加載畫面
        showLoading();
        var url = "/Home/GetProductTypes";
        $.ajax({
            url: url,         //请求链接 
            dataType: "json",
            success: function (result) {
                //將數據配合模版插入到#tree中
                $('#treeNodeTemplate').tmpl(result).appendTo($('#tree'));

                //初始化樹結構
                $('#tree').treeview({
                    collapsed: true,
                    animated: 'fast',
                    prerendered: true,
                    persist: 'location'
                });

                //綁定树節點事件
                $('.treeNode', '#tree').unbind('click').bind('click', function () {
                    $('.treeNode:not(.hover)', '#tree').removeClass('selected');
                    $(this).addClass('selected');

                    //加載產品
                    loadProductsByProductType();
                });
                $('.treeNode:odd', '#tree').addClass('odd');
                $('.treeNode:even', '#tree').addClass('even');

                //緩存ProductType
                productTypes = result;

                //隱藏加載提示
                hideLoading();

                $('.treeNode:first', '#tree').click();
            }
        });
    };
    //根據ProductType加載Product
    function loadProductsByProductType() {
        //顯示加載畫面
        showLoading();
        //當前選中的树節點
        var $selectedTreeNode = $('.treeNode.selected');
        //清空Product列表
        $('.product_selector_content_products').html("");

        var url = "/Home/GetProductsByProductType?id=" + $selectedTreeNode.attr('producttypeid');
        $.ajax({
            url: url,         //请求链接 
            dataType: "json",
            success: function (result) {
                //將數據配合模版插入到.product_selector_content_products中
                $('#metroGridTemplate').tmpl(result).appendTo($('.product_selector_content_products'));
                //初始化product grid
                $('.product').metro_grid();
                //隱藏加載提示
                hideLoading();
            }
        });
    }
    //調整所有metro_input_caption寬度
    function adjustMetroInputContain() {
        var maxCaptionWidth = $.fn.calcMaxWidth($('.metro_input_caption'));
        $('.metro_input_caption').each(function () {
            $(this).width(maxCaptionWidth);
        });
    }
    //打開產品選擇
    function openSelectProduct() {
        loadProductTypes();

        $('#ProductSelector').prependTo($('.metro_custom'));
        adjustProductSelector();

        $('#ProductSelector').show();
    }
    //取消產品選擇
    function cancelSelectProduct() {
        $('#ProductSelector').hide();
    }
    //確定選擇
    function confirmSelectProduct() {
        $selectedProduct = $('.metro_grid_row.selected', '.product');
        if ($selectedProduct.length == 0) {
            return;
        }
        addProduct($selectedProduct);
        $('#ProductSelector').hide();
    }
    //增加product
    function addProduct($selectedProduct) {
        var data = {
            ProductID: $('.productID', $selectedProduct).html(),
            ProductName: $('.productName', $selectedProduct).html(),
            ProductType: $('.productType', $selectedProduct).html(),
            ProductBrand: $('.productBrand', $selectedProduct).html(),
            ProductModel: $('.productModel', $selectedProduct).html(),
            ListPrice: $('.productPrice', $selectedProduct).html(),
            Price: $('.productPrice', $selectedProduct).html(),
            PriceStr: formatNumber($('.productPrice', $selectedProduct).html(), "#,###.00"),
            Qty: 1,
            TotalPrice: $('.productPrice', $selectedProduct).html(),
            TotalPriceStr: formatNumber( $('.productPrice', $selectedProduct).html(), "#,###.00"),
        };

        //檢查是否已經存在該Product
        var findedProduct = false;
        $('.productID', '.orderDetail').each(function () {
            if ($(this).html().trim() == data.ProductID) {
                $(this).parent().click();
                findedProduct = true;
            }
        });

        if (findedProduct)
            return;

        //將數據配合模版插入到order detail中
        var newRow = $('#metroGridRowTemplate_OrderDetail').tmpl(data);
        addItemToOrderDetail(newRow);
    }

    function newProduct() {
        var data = {
            ProductID: '',
            ProductName: '',
            ProductType: '',
            ProductBrand: '',
            ProductModel: '',
            ListPrice: '（無）',
            Price: 0,
            PriceStr: '0.00',
            Qty: 1,
            TotalPrice: 0,
            TotalPriceStr: '0.00',
        };

        var newRow = $('#metroGridRowTemplate_OrderDetail_NewProduct').tmpl(data);
        addItemToOrderDetail(newRow);
    }

    function addOrderDetails(){
        var $orderDetailList = $('item', $($('#orderDetailList').html()));
        $orderDetailList.each(function () {
            $this = $(this);
            var data = {
                ProductID: $this.attr('productID'),
                ProductName: $this.attr('name'),
                ProductType: $this.attr('type'),
                ProductBrand: $this.attr('brand'),
                ProductModel: $this.attr('model'),
                ListPrice: $this.attr('listPrice'),
                Price: parseFloat($this.attr('price')),
                PriceStr:$this.attr('price'),
                Qty: parseFloat($this.attr('qty')),
                TotalPrice:$this.attr('totalPrice'),
                TotalPriceStr:$this.attr('totalPrice'),
            };
            console.log(data);

            var newRow = $('#metroGridRowTemplate_OrderDetail').tmpl(data);
            addItemToOrderDetail(newRow);
        });
    }

    function addItemToOrderDetail(newRow)
    {
        newRow.appendTo($('.metro_grid_rows', '.orderDetail'));
        $('.orderDetail').metro_grid({
            initCell: function ($cell, $row, $column) {
                var $input = $('input', $cell);
                if ($input.length > 0) {
                    $input.width($column.width() - 1);
                    $input.unbind('change').bind('change', function () {
                        calcPrice();
                    });
                }
            }
        });
        newRow.click();
        calcPrice();
    }

    //移除product
    function removeProduct()
    {
        var $selectedRow = $('.metro_grid_row.selected','.orderDetail');

        if ($selectedRow.length == 0) {
            showMessage('請選擇需要移除的產品');
        }
        $selectedRow.remove();
        calcPrice();
    }
    //計算小計
    function calcPrice() {
        var totalListPrice = 0;
        $('.metro_grid_row', '.orderDetail').each(function () {
            var $row = $(this);
            var $qty = $('.od_Qty', $row).val();
            var $price = $('.od_Price', $row).val();

            if (isNaN($price)) {
                showError('價格只能輸入數字');
                $('.od_Price', $row).focus();
                return;
            }

            if (isNaN($qty)) {
                showError('數量只能輸入數字');
                $('.od_Qty', $row).focus();
                return;
            }

            $('.od_TotalPrice', $row).attr('od_TotalPrice',$qty * $price);
            $('.od_TotalPrice', $row).html(formatNumber($qty * $price,"#,###.00"));

            totalListPrice += parseFloat($('.od_TotalPrice', $row).attr('od_TotalPrice'));
        });
        $('#TotalPrice').html(formatNumber(totalListPrice,"#,###.00"));
    }
    //調整product_selector位置
    function adjustProductSelector() {
        var $overlay = $('.product_selector');
        var $overlay_content = $('.product_selector_contain');
        $overlay_content.css({ left: $overlay.width() / 2 - $overlay_content.width() / 2,
            top: $overlay.height() / 2 - $overlay_content.height() / 2
        });
    };
</script>
<data id="orderDetailList">
    @if (Model.OrderDetails != null)
    {
    <list>
        @foreach (var item in Model.OrderDetails)
        {
        <item productID='@item.ProductID' name='@item.ProductName' type='@item.ProductType' brand='@item.ProductBrand' model='@item.ProductModel' listPrice='@item.ListPrice' price='@item.Price' qty='@item.Qty' totalPrice='@item.TotalPrice'></item>
        }
    </list>
    }
</data>
